<?php
// 连接数据库
include_once('./config/config.php');

// 获取操作 action
$action = $_POST['action'] ?? '';
// 获取管理员用户名操作select_admin_username
if ($action === 'select_admin_username') {
  $username = isset($_POST['username']) ? trim($_POST['username']) : '';
  $sql = "SELECT * FROM `pre_admin` WHERE `username` = '$username'";
  $admin = find($sql);
  if ($admin) {
    echo json_encode(['code' => 0, 'msg' => '用户名已存在', 'data' => null]);
    exit;
  } else {
    echo json_encode(['code' => 1, 'msg' => '用户名可用', 'data' => null]);
    exit;
  }
}

// 删除管理员操作delete_admin
if ($action === 'delete_admin') {
  $id = $_POST['id'];
  // 查询一下这个id是否存在
  $sql = "SELECT * FROM `pre_admin` WHERE `id` = $id";
  $res = find($sql);
  if (!$res) {
    echo json_encode(['code' => 0, 'msg' => '管理员不存在', 'data' => null]);
    exit;
  }
  $result = del('admin', "`id`=$id");
  if ($result) {
    // 头像也要删除
    @is_file('.' . $res['avatar'] && unlink('.' . $res['avatar']));
    echo json_encode(['code' => 1, 'msg' => '删除管理员成功', 'data' => null]);
    exit;
  } else {
    echo json_encode(['code' => 0, 'msg' => '删除管理员失败', 'data' => null]);
    exit;
  }
}

// 获取部门操作select_department 
if ($action === 'select_department') {
  $sql = "SELECT * FROM `pre_department`";
  $res = all($sql);
  if ($res) {
    echo json_encode(['code' => 1, 'msg' => '查询部门成功', 'data' => $res]);
    exit;
  } else {
    echo json_encode(['code' => 0, 'msg' => '查询部门失败', 'data' => $res]);
    exit;
  }
}

// 删除学生操作student_delete
if ($action === 'student_delete') {
  $id = $_POST['id'];
  // 查询一下这个id是否存在
  $sql = "SELECT * FROM `pre_student` WHERE `id` = $id";
  $res = find($sql);
  if (!$res) {
    echo json_encode(['code' => 0, 'msg' => '学生不存在', 'data' => null]);
    exit;
  }
  $result = del('student', "`id`=$id");
  if ($result) {
    // 头像也要删除
    @is_file('.' . $res['avatar'] && unlink('.' . $res['avatar']));
    echo json_encode(['code' => 1, 'msg' => '删除学生成功', 'data' => null]);
    exit;
  } else {
    echo json_encode(['code' => 0, 'msg' => '删除学生失败', 'data' => null]);
    exit;
  }
}
